<?php

namespace app\service;

use app\model\Task;
class TaskService
{
    private $task;
    public function __construct()
    {
        $this->task = new Task;
    }

    public function list($params = [])
    {
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;
        $where = [];

        if(!empty($params['title'])) $where[] = ['title', 'like', '%'.trim($params['title']).'%'];

        if(isset($params['status']) && $params['status']!='' ) $where[]=['status','=',$params['status']];

        if(isset($params['task_category_id']) && $params['task_category_id']!='' ) $where[]=['task_category_id','=',$params['task_category_id']];

        $result = $this->task->with(['taskCategory'])->where($where)->order(['sort' => 'desc', 'updated_at'=>'desc','id' => 'desc'])->paginate([
            'list_rows'=> $pageSize,
            'page' => $page
        ])->append(['status_text','is_attachment_text']);

        return $result;
    }

    public function save($param){
        return $this->task->allowField(['title','cover', 'status', 'sort', 'task_category_id','content','attachment','price','is_attachment'])->create($param);
    }

    public function update($id, $param)
    {
        $task = $this->task->find($id);
        //数据库存在的字段才更新
        return $task->allowField(['title', 'cover','status', 'sort', 'task_category_id','content','attachment','price','is_attachment'])->save($param);
    }

    public function delete($id)
    {
        return $this->task->destroy($id);
    }

    public function read($id)
    {
        return $this->task->find($id);
    }

    public function getTaskVipPrice($taskPrice,$vip)
    {

    }

    public function all()
    {
        $memberId = request()->_mid;

        return $this->task->where(['status' => 1])
            ->join('percentage', 'percentage.task_id = task.id AND percentage.member_id = '.$memberId, 'LEFT')
            ->field('task.*,percentage.proportion')
            ->select();
    }
}
